var board = new Array();
var score = 0;
var hasConflicted = new Array();

var startx = 0;
var starty = 0;
var endx = 0;
var endy = 0;


//页面加载完以后执行
$(document).ready(function(){
    prepareForMobile();
    newgame();
    var newgamebtn = document.getElementById("newgamebutton");
	newgamebtn.addEventListener("click",function(){
		newgame();
	})
});

//移动端
function prepareForMobile(){

    if(documentWidth>500){
        gridContainerWidth = 500;
        cellSpace = 20;
        cellSideLength = 100;
    }

    $('#grid-container').css('width',gridContainerWidth - 2*cellSpace);
    $('#grid-container').css('height',gridContainerWidth - 2*cellSpace);
    $('#grid-container').css('padding', cellSpace);
    $('#grid-container').css('border-radius',0.02*gridContainerWidth);

    $('.grid-cell').css('width',cellSideLength);
    $('.grid-cell').css('height',cellSideLength);
    $('.grid-cell').css('border-radius',0.02*cellSideLength);
}

function newgame(){
    //初始化棋盘格
    init();
    //在随机两个格子生成数字
    generateOneNumber();
    generateOneNumber();
}

function init(){
    for(var i=0;i<4;i++)
        for(var j=0;j<4;j++){
            var gridCell = $('#grid-cell-'+i+"-"+j);
            gridCell.css('top', getPosTop(i,j));
            gridCell.css('left', getPosLeft(i,j));
        }
    for(var i=0;i<4;i++){
        board[i] = new Array();
        hasConflicted[i] = new Array();
        for(var j=0;j<4;j++){
            board[i][j] = 0;
            hasConflicted[i][j] = false;
        }
    }
    updateBoardView();
    score = 0;
}

function updateBoardView(){
    $(".number-cell").remove();
    for(var i=0;i<4;i++)
        for(var j=0;j<4;j++){
            $("#grid-container").append( '<div class="number-cell" id="number-cell-'+i+'-'+j+'"></div>' );
            var theNumberCell = $('#number-cell-'+i+'-'+j);
            if(board[i][j] == 0){
                theNumberCell.css('width','0px');
                theNumberCell.css('height','0px');
                theNumberCell.css('top',getPosTop(i,j) + cellSideLength/2 );
                theNumberCell.css('left',getPosLeft(i,j) + cellSideLength/2 );
            }
            else{
                theNumberCell.css('width',cellSideLength);
                theNumberCell.css('height',cellSideLength);
                theNumberCell.css('top',getPosTop(i,j));
                theNumberCell.css('left',getPosLeft(i,j));
                theNumberCell.css('background-color',getNumberBackgroundColor( board[i][j] ) );
                theNumberCell.css('color',getNumberColor( board[i][j] ) );
                theNumberCell.text( board[i][j] );
            }
            hasConflicted[i][j] = false;
        }
    $('.number-cell').css('line-height',cellSideLength+'px');
    $('.number-cell').css('font-size',0.6*cellSideLength+'px');
}

function generateOneNumber(){

    if(nospace(board)){
    	return false;
    }
     
    //随机一个位置
    var randx = parseInt(Math.floor(Math.random()*4));
    var randy = parseInt(Math.floor(Math.random()*4));

    var times = 0;
    while(times<50){
        if(board[randx][randy] == 0){
        	break;
        }
        randx = parseInt(Math.floor(Math.random()*4));
        randy = parseInt(Math.floor(Math.random()*4));
        times++;
    }
    if(times==50){
        for(var i=0;i<4;i++){
        	for(var j=0;j<4;j++){
                if(board[i][j] == 0){
                    randx = i;
                    randy = j;
                }
            }
        }  
    }

    //随机一个数字
    var randNumber = Math.random() < 0.5 ? 2 : 4;

    //在随机位置显示随机数字
    board[randx][randy] = randNumber;
    showNumberWithAnimation(randx,randy,randNumber);

    return true;
}

//键盘上下左右控制
document.addEventListener("keydown",function(event){
	if(event.keyCode == 37){
		if(moveLeft()){
			setTimeout("generateOneNumber()",210);
            setTimeout("isgameover()",300);
		}
	}
	if(event.keyCode == 38){
		if(moveUp()){
			setTimeout("generateOneNumber()",210);
            setTimeout("isgameover()",300);
		}
	}
	if(event.keyCode == 39){
		if(moveRight()){
			setTimeout("generateOneNumber()",210);
            setTimeout("isgameover()",300);
		}
	}
	if(event.keyCode == 40){
		if(moveDown()){
			setTimeout("generateOneNumber()",210);
            setTimeout("isgameover()",300);
		}
	}
})




//移动端触摸控制
document.addEventListener('touchstart',function(event){
    startx = event.touches[0].pageX;
    starty = event.touches[0].pageY;
});

document.addEventListener('touchend',function(event){
    endx = event.changedTouches[0].pageX;
    endy = event.changedTouches[0].pageY;

    var deltax = endx - startx;
    var deltay = endy - starty;

    if(Math.abs(deltax)<0.3*documentWidth && Math.abs(deltay)<0.3*documentWidth){
    	return;
    }
        

    if(Math.abs(deltax)>=Math.abs(deltay)){
        if(deltax>0){
            //向右移动
            if(moveRight()){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
        }
        else{
            //向左移动
            if(moveLeft()){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
        }
    }
    else{
        if(deltay>0){
           	//向下移动
            if(moveDown()){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
        }
        else{
            //向上移动
            if(moveUp()){
                setTimeout("generateOneNumber()",210);
                setTimeout("isgameover()",300);
            }
        }
    }
});

function isgameover(){
    if(nospace(board) && nomove(board)){
        gameover();
    }
}

function gameover(){
    alert("游戏结束，请重新开始新的游戏!");
}

function moveLeft(){

    if(!canMoveLeft(board)){
    	return false;
    }
        

    //moveLeft
    for(var i=0;i<4;i++)
        for(var j=1;j<4;j++){
            if(board[i][j]!=0){
                for(var k=0;k<j;k++){
                    if(board[i][k] == 0 && noBlockHorizontal(i,k,j,board)){
                        showMoveAnimation(i,j,i,k);
                        board[i][k] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if(board[i][k] == board[i][j] && noBlockHorizontal(i,k,j,board) && !hasConflicted[i][k]){
                        showMoveAnimation(i,j,i,k);
                        board[i][k] += board[i][j];
                        board[i][j] = 0;
                        //增加分数
                        score += board[i][k];
                        updateScore(score);
                        hasConflicted[i][k] = true;
                        continue;
                    }
                }
            }
        }
    setTimeout("updateBoardView()",200);
    return true;
}

function moveRight(){
    if(!canMoveRight(board)){
    	return false;
    }
        
    //moveRight
    for(var i=0;i<4;i++)
        for(var j=2;j>=0;j--){
            if(board[i][j] != 0){
                for(var k=3;k>j;k--){
                    if(board[i][k] == 0 && noBlockHorizontal(i,j,k,board)){
                        showMoveAnimation(i,j,i,k);
                        board[i][k] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if(board[i][k] == board[i][j] && noBlockHorizontal(i,j,k,board) && !hasConflicted[i][k]){
                        showMoveAnimation(i,j,i,k);
                        board[i][k] += board[i][j];
                        board[i][j] = 0;
                        score += board[i][k];
                        updateScore(score);
                        hasConflicted[i][k] = true;
                        continue;
                    }
                }
            }
        }
    setTimeout("updateBoardView()",200);
    return true;
}

function moveUp(){
    if(!canMoveUp(board)){
    	return false;
    }
        
    for(var j=0;j<4;j++)
        for(var i=1;i<4;i++){
            if(board[i][j] != 0){
                for(var k=0;k<i;k++){
                    if(board[k][j] == 0 && noBlockVertical(j,k,i,board)){
                        showMoveAnimation(i,j,k,j);
                        board[k][j] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if(board[k][j] == board[i][j] && noBlockVertical(j,k,i,board) && !hasConflicted[k][j]){
                        showMoveAnimation(i,j,k,j);
                        board[k][j] += board[i][j];
                        board[i][j] = 0;
                        score += board[k][j];
                        updateScore(score);
                        hasConflicted[k][j] = true;
                        continue;
                    }
                }
            }
        }
    setTimeout("updateBoardView()",200);
    return true;
}

function moveDown(){
    if(!canMoveDown(board)){
    	return false;
    }
       
    //moveDown
    for(var j=0;j<4;j++)
        for(var i=2;i>=0;i--){
            if(board[i][j] != 0){
                for(var k=3;k>i;k--){
                    if(board[k][j] == 0 && noBlockVertical(j,i,k,board)){
                        showMoveAnimation(i,j,k,j);
                        board[k][j] = board[i][j];
                        board[i][j] = 0;
                        continue;
                    }
                    else if(board[k][j] == board[i][j] && noBlockVertical(j,i,k,board) && !hasConflicted[k][j]){
                        showMoveAnimation(i,j,k,j);
                        board[k][j] += board[i][j];
                        board[i][j] = 0;
                        score += board[k][j];
                        updateScore(score);
                        hasConflicted[k][j] = true;
                        continue;
                    }
                }
            }
        }
    setTimeout("updateBoardView()",200);
    return true;
}













/*
 * 控制动画的部分
 */
//------开始
function showNumberWithAnimation(i,j,randNumber){
    var numberCell = $('#number-cell-' + i + "-" + j);
    numberCell.css('background-color',getNumberBackgroundColor(randNumber));
    numberCell.css('color',getNumberColor(randNumber));
    numberCell.text(randNumber);

    numberCell.animate({
        width:cellSideLength,
        height:cellSideLength,
        top:getPosTop(i,j),
        left:getPosLeft(i,j)
    },50);
}

function showMoveAnimation(fromx,fromy,tox,toy){
    var numberCell = $('#number-cell-' + fromx + '-' + fromy);
    numberCell.animate({
        top:getPosTop(tox,toy),
        left:getPosLeft(tox,toy)
    },200);
}

function updateScore(score){
    $('#score').text(score);
}
//-------------结束


/*
 * 判断条件以及添加背景
 */
//----------开始
//适应屏幕
documentWidth = window.screen.availWidth;
gridContainerWidth = 0.92 * documentWidth;
cellSideLength = 0.18 * documentWidth;
cellSpace = 0.04*documentWidth;

function getPosTop(i,j){
    return cellSpace + i*(cellSpace+cellSideLength);
}

function getPosLeft(i,j){
    return cellSpace + j*(cellSpace+cellSideLength);
}
//添加背景颜色
function getNumberBackgroundColor(number){
    switch(number){
        case 2:
        	return "#eee4da";
        	break;
        case 4:
        	return "#ede0c8";
        	break;
        case 8:
        	return "#f2b179";
        	break;
        case 16:
        	return "#f59563";
        	break;
        case 32:
        	return "#f67c5f";
        	break;
        case 64:
        	return "#f65e3b";
        	break;
        case 128:
        	return "#edcf72";
        	break;
        case 256:
        	return "#edcc61";
        	break;
        case 512:
        	return "#9c0";
        	break;
        case 1024:
        	return "#33b5e5";
        	break;
        case 2048:
        	return "#09c";
        	break;
    }
    return "black";
}
//添加字体颜色
function getNumberColor(number){
    if(number<=4){
    	return "#776e65";
    }
    return "white";
}
//判断是否有空间
function nospace(board){
    for(var i=0;i<4;i++){
    	for(var j=0;j<4;j++){
        	if(board[i][j] == 0){
            	return false;
            }
        }
    }     
    return true;
}
//判断是否能移动
function canMoveLeft(board){
    for(var i=0;i<4;i++){
    	for(var j=1;j<4;j++){
        	if(board[i][j] != 0){
            	if(board[i][j-1] == 0 || board[i][j-1] == board[i][j]){
                	return true;
                }
            }
        }
    }
    return false;
}

function canMoveRight(board){
    for(var i=0;i<4;i++){
    	for(var j=2;j>=0;j--){
        	if(board[i][j] != 0){
            	if(board[i][j+1] == 0 || board[i][j+1] == board[i][j]){
                	return true;
                }
            }
        }
    }
    return false;
}

function canMoveUp(board){
    for(var j=0;j<4;j++){
    	for(var i=1;i<4;i++){
        	if(board[i][j] != 0){
            	if(board[i-1][j] == 0 || board[i-1][j] == board[i][j]){
                	return true;
                }
            }
        }
    }
    return false;
}

function canMoveDown(board){
    for(var j=0;j<4;j++){
    	for(var i=2;i>=0;i--){
        	if(board[i][j] != 0){
            	if(board[i+1][j] == 0 || board[i+1][j] == board[i][j]){
                	return true;
                }
            }
        }
    }
    return false;
}

//判断是否有障碍
function noBlockHorizontal(row,col1,col2,board){
    for(var i=col1+1;i<col2;i++){
    	if(board[row][i] != 0){
        	return false;
        }
    }     
    return true;
}

function noBlockVertical(col,row1,row2,board){
    for(var i=row1+1;i<row2;i++){
    	if(board[i][col] != 0){
        	return false;
        }
    }    
    return true;
}

function nomove(board){
    if(canMoveLeft(board) || canMoveRight(board) || canMoveUp(board) || canMoveDown(board)){
    	return false;
    }
    return true;
}

//-----------------结束